//
//  HomeTableViewController.swift
//  zyqWeibo
//
//  Created by 张亚琼 on 15/6/23.
//  Copyright © 2015年 张亚琼. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseViewController,WeiboCellDelegate {

    // 定义行高的缓存数组 [weibo的id:行高]
    lazy var rowHightCache = [Int:CGFloat]()
    
    // 存放模型的数组
    var weiboList: [Weibo]?{
        didSet {
            
            // 停止刷新
            refreshControl?.endRefreshing()
            // 刷新数据
            tableView.reloadData()
        }
    }
    
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        visitorView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        if sharedUserAccount == nil{
            return
        }
        setUpNavigationBar()
        prepareTableView()
        loadData()

        // 刷新控件的大小是（375，60）
        refreshControl = YQRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    // 准备tableView
    func prepareTableView() {
        // 注册cell
        tableView.registerClass(WeiboForwardCell.self, forCellReuseIdentifier: YQForwardWeiboCellReuseIdentifier)
        tableView.registerClass(WeiboNormalCell.self, forCellReuseIdentifier: YQNormalWeiboCellReuseIdentifier)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    // 加载数据
    func loadData() {
        // 把最新微博的id传入
       var since_id = weiboList?.first?.id ?? 0
        var max_id = 0
        // 最后一个微博的id传入。如果下拉刷新标识为true（在到达最后一个cell的时候置为true）
        if pullRefreshFlag {
            since_id = 0
            max_id = weiboList?.last?.id ?? 0
        }
        
        // 加载网络数据
        Weibo.loadStatus(max_id,since_id: since_id) {(weibos, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("咋回事，网络不给力哦")
                return
            }
            if weibos == nil {
                print("木有数据哦")
                return
            }
            if since_id > 0 {
                self.weiboList = weibos! + self.weiboList!
            }else if max_id > 0 && self.pullRefreshFlag {
                self.weiboList = self.weiboList! + weibos!
                self.pullRefreshFlag = false
            }else {
                self.weiboList = weibos
            }
        }
            
        
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 在这里开启动画
        // 这里也可以访问到访问视图
        visitorView?.starAnimation()
    }
    
    
    //MARK: - 数据源方法
    // 有多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weiboList?.count ?? 0
    }
    // 每行显示什么
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let weibo = weiboList![indexPath.row]
        let ID = WeiboCell.getReuseID(weibo)
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! WeiboCell
        // 设置代理
        cell.pictureDelegate = self

        // 用户看到最后一行的时候后台开始刷新数据
        if indexPath.row == (weiboList!.count - 1) {
            // 开始刷新
            pullRefreshFlag = true
            loadData()
        }
        cell.weibo = weibo
        return cell
    }
    // 计算行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
         let weibo = weiboList![indexPath.row]
        // 如果缓存中已经有了对应的行高，直接返回
        if rowHightCache[weibo.id] != nil {
            return rowHightCache[weibo.id]!
        }
        
        // 根据不同的ID获取不同类型的cell
        let ID = WeiboCell.getReuseID(weibo)
        var classType:AnyClass = WeiboNormalCell.self
        if ID == YQForwardWeiboCellReuseIdentifier {
            classType = WeiboForwardCell.self
        }
        let cell = classType.new() as! WeiboCell
        // 如果缓存中没有，放入缓存再返回
        rowHightCache[weibo.id] = cell.rowHight(weibo)
        
        return cell.rowHight(weibo)
    }
    //MARK: 微博cell的代理方法
    func weiboCellDidSelectedImage(cell: WeiboCell, imageIndex: Int) {
        if cell.weibo?.largePicUrl == nil {
            return
        }
        let vc = PhotoBrowserViewController(urls: cell.weibo!.largePicUrl!, index: imageIndex)
        // 设置转场代理
        vc.transitioningDelegate = self
        // 设置转场模式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        // 
        presentViewController(vc, animated: true, completion: nil)
    }
    
    /// 导航栏右侧按钮被点击
    func rightItemButtonClicked(){
        let storyBoard = UIStoryboard(name: "QRCode", bundle: nil)
    presentViewController(storyBoard.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    /// 设置导航栏
    private func setUpNavigationBar() {
        // 先判断用户是否登录，没有登录直接返回
        if sharedUserAccount == nil {
            return
        }
        
        // 设置左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", hilightedImage: nil)        // 右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", hilightedImage: nil)
        // > 获取button
        let btn = navigationItem.rightBarButtonItem!.customView as! UIButton
        btn.addTarget(self, action: "rightItemButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置标题，标题是用户名
        let name = sharedUserAccount!.name!
        // 使用自定义button
        let titleButton = HomeTitleButton.button(name)
        titleButton.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
        
    }
    
    // 转场动画代理(写成变量是为了可以设置frame)
    let popoverAnimator = PopoverAnimator()
    // 点击标题按钮
    func titleButtonClicked() {
        // 加载storyboard
        let storyBoard = UIStoryboard(name: "FriendGroup", bundle: nil)
        // 根据storyboard的ID获取对应的初始化控制器
        let vc = storyBoard.instantiateViewControllerWithIdentifier("FriendGroupStoryBoard")
        
        // 设置转场的代理(在extension中遵守UIViewControllerTransitioningDelegate协议)
        vc.transitioningDelegate = popoverAnimator
        // 设置视图展现的frame
        let x = (view.bounds.width - 200) * 0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 200, 300)
        // 设置转场的模式为自定义模式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        // 将这个控制器modal出来
        presentViewController(vc, animated: true, completion: nil)
        
        
    }
    // 上拉刷新标识
    private var pullRefreshFlag = false
}
//MARK: 转场动画
var isPresented = false
extension HomeTableViewController:UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
    /// 第一个协议 UIViewControllerTransitioningDelegate 的代理方法
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // 该方法返回的是由谁提供转场modal的对象
        isPresented = true
        return self
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // 返回提供dismiss的对象
        isPresented = false
        return self
    }
    
    /// 第二个协议 UIViewControllerAnimatedTransitioning 的代理方法
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        if isPresented {
            // 添加toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView?.alpha = 0
            // 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView?.alpha = 1.0
                }) { (_) -> Void in
                    // 告诉动画完成
                    transitionContext.completeTransition(true)
            }
        }else {
            // 动画
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView?.alpha = 0
                }, completion: { (_) -> Void in
                    // 先移除fromView
                    targetView?.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
    }
    
    
    
}